/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Thread_WIN32.h"
#include <cassert>
#include "UGame/Macros.h"
#include "Runnable.h"

namespace UGame {
namespace System {

    ThreadImpl::ThreadImpl(void)
        : _id(0)
        , _handle(-1L)
        , _runnable(NULL)
    {

    }

    ThreadImpl::~ThreadImpl(void)
    {
        /* Close thread handle */
        if (_handle != -1L) {
            CloseHandle((HANDLE)_handle);
        }
    }

    bool ThreadImpl::StartImpl(Runnable* _Runnable)
    {
        UASSERT(_handle == -1L);
        _runnable = _Runnable;
        _handle = _beginthreadex(NULL, 0, ThreadImpl::_Proc,
            this, 0, (unsigned int*)&_id);
        return _handle != -1L;
    }

    void ThreadImpl::JoinImpl(void)
    {
        UASSERT(_handle != -1L);
        if (_handle != -1L) {
            WaitForSingleObject(HANDLE(_handle), INFINITE);
        }
    }

    bool ThreadImpl::JoinableImpl(void)
    {
        return _handle != -1L;
    }

    bool ThreadImpl::SetPriorityImpl(int _Priority)
    {
        return SetThreadPriority((HANDLE)_handle, _Priority) != FALSE;
    }

    ThreadImpl::ID ThreadImpl::GetCurrentIDImpl(void)
    {
        return GetCurrentThreadId();
    }

    void ThreadImpl::SleepImpl(long _Milliseconds)
    {
        Sleep((DWORD)_Milliseconds);
    }

    unsigned int ThreadImpl::_Proc(void* _Arg)
    {
        UASSERT(_Arg != NULL);
        ThreadImpl* _TH = static_cast<ThreadImpl*>(_Arg);
        _TH->_runnable->Run();
        return 0;
    }

}}